<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HealthDiaryController extends ApiController
{

    public function __construct()
    {
        parent::__construct();
        $user = Auth::user();
        if (empty($user->is_evaluate)) {
            return $this->failed("用户未参与评测");
        }
    }

    /**
     * 获取健康日记部分数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $date = $request->input("date", date("Y-m-d"));
        $user = Auth::user();
        $user_id = $user->id;
        if (!valid_date($date)) {
            return $this->failed("日期选择错误");
        }
        $date = date("Ymd", strtotime($date));
        $health_diary = DB::table('user_health_diary')->select('id', 'all_caloric', 'eat_caloric', 'sport_caloric', 'drink_count')->where([['user_id', '=', $user_id], ['date', '=', $date]])->first();
        if (empty($health_diary)) {
            $report = DB::table('user_health_report')->where(['user_id' => $user_id])->first();
            if (empty($report)) {
                return $this->failed("用户未参与评测");
            }
            $insert_id = DB::table('user_health_diary')->insertGetId(['user_id' => $user_id, 'date' => $date, 'all_caloric' => $report->caloric]);
            $health_diary = ['id' => $insert_id, 'all_caloric' => $report->caloric, 'eat_caloric' => 0,  'sport_caloric' => 0, 'drink_count' => 0];
        }
        return $this->success($health_diary);
    }

    /**
     * 饮食分析
     * 三大产能营养素供能比及能量系数  ：  蛋白质  10  %~  15%  （  每克蛋白质的能量系数为  4  kcal  ），脂肪  20  %~  30%  （每克脂肪的能量系数为  9  kcal  ），碳水化合物  55  %~  65%  （每克碳水化合物的能量系数为  4  kcal  ）。
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function analyse(Request $request)
    {
        $id = $request->input("id", 0);
        if (empty($id)) {
            return $this->failed("参数错误");
        }
        $user = Auth::user();
        $user_id = $user->id;

        $health_diary = DB::table('user_health_diary')->where(['id' => $id, 'user_id' => $user_id])->first();
        if(empty($health_diary)) {
            return $this->failed("参数错误");
        }
        $report = DB::table('user_health_report')->where(['user_id' => $user_id])->first();
        $is_exist_eat = DB::table('user_health_eat')->where(['diary_id' => $id])->first();
        if (empty($is_exist_eat)) {
            return $this->failed("还未添加饮食记录");
        }
        $eat_list = DB::table('user_health_eat')->where(['diary_id' => $id])->first([
            \DB::raw('SUM(caloric) as caloric'),
            \DB::raw('SUM(fat_caloric) as fat_caloric'),
            \DB::raw('SUM(protein_caloric) as protein_caloric'),
            \DB::raw('SUM(carbohydrate_caloric) as carbohydrate_caloric')
        ]);

        //计算比率
        $fat_rate = round($eat_list->fat_caloric / $eat_list->caloric * 100);
        $protein_rate = round($eat_list->protein_caloric / $eat_list->caloric * 100);
        $carbohydrate_rate = 100 - $fat_rate - $protein_rate;

        //计算重量
        $fat_weight = round($eat_list->fat_caloric / 9, 1);
        $protein_weight = round($eat_list->protein_caloric / 4, 1);
        $carbohydrate_weight = round($eat_list->carbohydrate_caloric / 4, 1);

        //计算标准
        $min_fat_weight = round($report->min_caloric * 0.2 / 9, 1);
        $max_fat_weight = round($report->max_caloric * 0.3 / 9, 1);

        $min_protein_weight = round($report->min_caloric * 0.1 / 4, 1);
        $max_protein_weight = round($report->max_caloric * 0.15 / 4, 1);

        $min_carbohydrate_weight= round($report->min_caloric * 0.55 / 4, 1);
        $max_carbohydrate_weight = round($report->max_caloric * 0.65 / 4, 1);

//        if ($fat_weight < $min_fat_weight) {
//            $fat_compare = -1;
//            $diff_fat_weight = $min_fat_weight - $fat_weight;
//            $fat_analyse = "您今日的脂肪摄入量为{$fat_weight}g，还应该补充摄入{$diff_fat_weight}g。必需脂肪酸不仅可调节血脂、防治冠心病，且与智力发育、记忆等生理功能相关。富含ω-3脂肪酸的有亚麻籽、菜籽油，三文鱼、奶酪、牛油果，其他油类推荐橄榄油、山茶油。每日可适当吃一小把新鲜原味的多种坚果，如花生、核桃、夏威夷果、大杏仁、榛子、碧根果、开心果、松子、腰果等，补充优质脂肪酸。";
//        } elseif ($fat_weight > $max_fat_weight) {
//            $fat_compare = 1;
//            $diff_fat_weight = $fat_weight - $max_fat_weight;
//            $fat_analyse = "您今日的脂肪摄入量为{$fat_weight}g，超出推荐量{$diff_fat_weight}g。过多的饱和脂肪酸不利于机体健康，也会影响您的完美体型。建议您适当减少奶油、蛋糕、食用油、肥肉、油炸、煎烤类食物，保证充足的优质脂肪，如坚果、鱼肉等，食不过量。";
//        } else {
//            $fat_compare = 0;
//            $fat_analyse = "";
//        }
//
//        if ($protein_weight < $min_protein_weight) {
//            $protein_compare = -1;
//            $diff_protein_weight = $min_protein_weight - $protein_weight;
//            $protein_analyse = "您今日的蛋白质摄入量为{$protein_weight}g，还应该补充摄入{$diff_protein_weight}g。优质蛋白质应占总蛋白质的1/3~1/2。建议您可适当摄入鱼、奶、瘦肉、蛋类及大豆类食物，如鳕鱼、带鱼、黄鱼、秋刀鱼、金枪鱼等海鱼，鸡脯肉、牛肉、牛奶、驴肉、虾肉、鸡蛋以及豆腐、现磨豆浆等豆制品。";
//        } elseif ($protein_weight > $max_protein_weight) {
//            $protein_compare = 1;
//            $diff_protein_weight = $protein_weight - $max_protein_weight;
//            $protein_analyse = "您今日的蛋白质摄入量为{$protein_weight}g，超出推荐量{$diff_protein_weight}g。建议您调整膳食比例，在保证优质蛋白质充足的情况下，鱼、肉、蛋、奶类可适当减少摄入，食不过量。";
//        } else {
//            $protein_compare = 0;
//            $protein_analyse = "";
//        }
//
//        if ($carbohydrate_weight < $min_carbohydrate_weight) {
//            $carbohydrate_compare = -1;
//            $diff_carbohydrate_weight = $min_carbohydrate_weight - $carbohydrate_weight;
//            $carbohydrate_analyse = "您今日的碳水化合物摄入量为{$carbohydrate_weight}g，还应该摄入{$diff_carbohydrate_weight}g。由于葡萄糖是人体大脑唯一的能量来源，为了保持大脑充足的能量供应，建议您可适当增加主食等复合糖类食物，如全麦面包、玉米、番薯、杂豆饭、藜麦、薏米、糙米、燕麦等。且用充足的碳水化合物来供能可以节省蛋白质，使其充分发挥修复细胞和组织的功效。注：不建议直接进食麦芽糖、  白糖、糖浆等精炼糖类，精炼糖进入人体后释放能量的速度比较快，易导致体内血糖突然升高和下降，反而不利于环节大脑疲劳。）";
//        } elseif ($carbohydrate_weight > $max_carbohydrate_weight) {
//            $carbohydrate_compare = 1;
//            $diff_carbohydrate_weight =  $carbohydrate_weight - $max_carbohydrate_weight;
//            $carbohydrate_analyse = "您今日的碳水化合物摄入量为{$carbohydrate_weight}g，超出推荐量{$diff_carbohydrate_weight}g。建议您适当减少精白米面的摄入，多纤维蔬菜、魔芋等食物可适当增加饱腹感而不增加热量，合理的进餐顺序也可帮助您达到平衡膳食，如汤水类--蔬菜类--菌菇类--肉鱼类--主食，食不过量。";
//        } else {
//            $carbohydrate_compare = 0;
//            $carbohydrate_analyse = "";
//        }

        return $this->success(['analyse' => [
            'fat_rate'                  => $fat_rate,
            'protein_rate'              => $protein_rate,
            'carbohydrate_rate'         => $carbohydrate_rate,
            'fat_weight'                => $fat_weight,
            'protein_weight'            => $protein_weight,
            'carbohydrate_weight'       => $carbohydrate_weight,
            'min_fat_weight'            => $min_fat_weight,
            'max_fat_weight'            => $max_fat_weight,
            'min_protein_weight'        => $min_protein_weight,
            'max_protein_weight'        => $max_protein_weight,
            'min_carbohydrate_weight'   => $min_carbohydrate_weight,
            'max_carbohydrate_weight'   => $max_carbohydrate_weight,
//            'fat_compare'               => $fat_compare,
//            'protein_compare'           => $protein_compare,
//            'carbohydrate_compare'      => $carbohydrate_compare,
//            'fat_analyse'               => $fat_analyse,
//            'protein_analyse'           => $protein_analyse,
//            'carbohydrate_analyse'      => $carbohydrate_analyse,
        ]]);
    }

    public function getDiaryRecord(Request $request)
    {
        $start_date = $request->input("start_date");
        $end_date = $request->input("end_date");

        $user = Auth::user();
        $user_id = $user->id;
        if (!valid_date($start_date) || !valid_date($end_date)) {
            return $this->failed("日期选择错误");
        }
        $start_date = date("Ymd", strtotime($start_date));
        $end_date = date("Ymd", strtotime($end_date));
        if ($end_date < $start_date) {
            return $this->failed("日期选择错误");
        }
        $date = DB::table('user_health_diary')->where('user_id', $user_id)->whereBetween('date', [$start_date, $end_date])->pluck('date');
        return $this->success(['date' => $date]);
    }

}
